package com.example.lib_base.base.mvp.view;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.view.View;

import com.example.lib_base.base.mvp.presenter.BasePresenter;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * @author yedong
 * @date 2019/1/11
 * MVP中V层的activity基类
 */
public abstract class BaseMvpActivity<V, P extends BasePresenter<V>> extends RxAppCompatActivity {
    public Activity mActivity;
    public P mPresenter;

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        mActivity = this;
    }

    @Override
    public void setContentView(View view) {
        super.setContentView(view);
        mActivity = this;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        mPresenter = createPresenter();
        if (mPresenter != null){
            mPresenter.attachView((V) this);
        }
        setContentView(getLayoutId());
        initData();
        initView();
        initEvent();
        loadData();
    }


    /**
     * 获取布局id
     *
     * @return
     */
    protected abstract int getLayoutId();

    /**
     * 创建P层
     *
     * @return
     */
    protected abstract P createPresenter();

    /**
     * 初始化数据（接收activity间的传值）
     */
    protected void initData() {

    }

    /**
     * 初始化View
     */
    protected abstract void initView();

    /**
     * 初始化事件
     */
    protected void initEvent() {

    }

    /**
     * 加载数据
     */
    protected void loadData() {

    }

    /**
     * 通过id控件查找控件
     *
     * @param id
     * @param <T>
     * @return
     */
    public <T extends View> T $(@IdRes int id) {
        return findViewById(id);
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        super.onDestroy();
    }

    @Subscribe
    public void eventBusDefault(Object o) {
        // do nothing
    }
}
